package dao;
//封装DBUtil类，通过这个类来完成数据库连接建立和资源回收
import org.sqlite.SQLiteDataSource;

import javax.sql.DataSource;
import java.sql.*;

public class DBUtil {
    //使用单例模式来提供DataSource
    private static volatile DataSource dataSource = null;
    public static DataSource getDataSource(){
        if (dataSource == null){
            synchronized (DBUtil.class){
                if (dataSource == null){
                    dataSource = new SQLiteDataSource();
                    ((SQLiteDataSource)dataSource).setUrl("jdbc:sqlite://E:/新建文件夹/sqlite-tools-win32-x86-3420000/" +
                            "sqlite-tools-win32-x86-3420000/fileSearcher.db");
                }
            }
        }
        return dataSource;
    }

    //获取数据库连接对象
    public static Connection getConnection() throws SQLException {

     return getDataSource().getConnection();
    }

    //关闭资源

    //                                 建立连接          执行SQL语句           从数据库中检索数据
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
